package com.yang.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class HeaderFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("Authorization");
        if (token != null) {
            currentContext.addZuulRequestHeader("Authorization", token);
            currentContext.setSendZuulResponse(true);
            currentContext.setResponseStatusCode(200);
            System.out.println("请求放行========>");
            return null;
        }
        currentContext.setSendZuulResponse(false); // 过滤
        currentContext.setResponseStatusCode(401);
        HttpServletResponse response = currentContext.getResponse();
        response.setCharacterEncoding("UTF-8");
        currentContext.setResponseBody("{'message':'token为空'}");
        System.out.println("请求被过滤");
        return null;
    }
}
